#include <font_manager.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <wchar.h>
#include <sys/ioctl.h>
#include <freetype2/ft2build.h>
#include <font_manager.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

FT_Face  g_tface;
static int g_ifont_size = 12;
static int FreetypeInin(char *afilename)
{   
    int error;
    FT_Library  library;


    error = FT_Init_FreeType( &library );              /* initialize library */
    if( error )
    {
        printf("FT_Init_FreeType error\n");
        return -1;
    }
    
    error = FT_New_Face( library, afilename, 0, &g_tface ); /* create face object */
    if( error )
    {
        printf("FT_New_Face error\n");
        return -1;
    }
    FT_Set_Pixel_Sizes(g_tface, g_ifont_size, 0);// 设置默认字体大小
    return  0;

}




static int SetFreetypeSize(int iFontSize)
{
    int ret = 0;
    ret = FT_Set_Pixel_Sizes(g_tface, iFontSize, 0);// 设置默认字体大小
    if(ret)
    {
        return -1;
    }    
    return 0;
}




static int GetFreetypeBitmap(unsigned int dwCode, PFontBitmap ptFontBitmap)
{
    int error;
    FT_Vector pen;
    FT_GlyphSlot slot = g_tface->glyph;

    pen.x = ptFontBitmap->iCurOriginX * 64; /* 单位: 1/64像素 */
    pen.y = ptFontBitmap->iCurOriginY * 64; /* 单位: 1/64像素 */

    FT_Set_Transform(g_tface, 0, &pen);
    error = FT_Load_Char(g_tface, dwCode, FT_LOAD_RENDER);
        if (error)
        {
            printf("FT_Load_Char error\n");
            return -1;
        }
    ptFontBitmap->pucBuffer     =  slot->bitmap.buffer;
    ptFontBitmap->tRegion.iLeftUpX      =  slot->bitmap_left  ;
    ptFontBitmap->tRegion.iLeftUpY      =  ptFontBitmap->iCurOriginY*2 - slot->bitmap_top  ;    
    ptFontBitmap->iNextOriginX  =  ptFontBitmap->iCurOriginX + slot->advance.x /64 ;
    ptFontBitmap->iNextOriginY  =  ptFontBitmap->iCurOriginY;  
    ptFontBitmap->tRegion.iHeigh         =  slot->bitmap.rows;  
    ptFontBitmap->tRegion.iWidth        =  slot->bitmap.width;  

return 0;

}

static FontOrp g_tFreetypeOrp = {
    .name = "Freetype",
    .FontInin = FreetypeInin,
    .SetFontSize     = SetFreetypeSize,
    .GetFontBitmap     = GetFreetypeBitmap,
};

void FreetypeRegisterFont(void)
{
    RegisterFontOrpForGround(&g_tFreetypeOrp);
}



